package com.xmut.bs.handaccount.util;

import android.text.TextUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;

/**
 * Author Dollkey
 * Date 2017/9/7 9:47.
 */

public class StringUtil {

    public static boolean isNull(String str) {
        return str == null || str.isEmpty() || str.trim().equals("");
    }

    public static String notNull(String str) {
        return isNull(str)?"":str;
    }

    public static int getInteger(String str,int defaultValue) {
        try {
            defaultValue = Integer.valueOf(str);
        }catch (Exception e){

        }
        return defaultValue;
    }

    public static double getDouble(String str,double defaultValue) {
        try {
            defaultValue = Double.valueOf(str);
        }catch (Exception e){

        }
        return defaultValue;
    }

    public static String calculation2Decimal(String price,int count){
        return doubleToString(Double.valueOf(price) * count);
    }

    public static String calculation2Decimal(Float price,int count){
        return doubleToString(price * count);
    }

    //"?x-oss-process=image/resize,w_100,h_100/quality,Q_50")
    public static String imageCompress(int w,int h,int q){
        return "?x-oss-process=image/resize,w_".concat(String.valueOf(w))
                .concat(",h_").concat(String.valueOf(h))
                .concat("/quality,Q_").concat(String.valueOf(q));
    }

    /**
     * double转String,保留小数点后两位
     * @param num
     * @return
     */
    public static String doubleToString(double num){
        //使用0.00不足位补0，#.##仅保留有效位
        return new DecimalFormat("0.00").format(num);
    }

    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
}
